package admin

import (
	"ia/apps/admin/dto/oin"
	oinadmin "ia/apps/admin/dto/oin/admin"
	"ia/common/icasbin"
	modeladmin "ia/common/model/admin"
	"ia/common/storage"
	"strconv"

	"github.com/kataras/iris/v12"
	"gorm.io/gorm"
)

type AdminRoleService interface {
	Create(modeladmin.AdminRole) error
	Edit(modeladmin.AdminRole) error
	DeleteByIdList([]int64) error
	GetTable(oin.VxeTableIn) ([]*modeladmin.AdminRole, int64, error)
	GetList() ([]*modeladmin.AdminRole, error)
	Grant(oinadmin.AdminRoleGrant) error
	Owned(int64) (iris.Map, error)
}

func NewAdminRoleService() *adminRoleService {
	return &adminRoleService{}
}

type adminRoleService struct{}

func (impl *adminRoleService) Create(in modeladmin.AdminRole) (err error) {
	err = storage.GDB1.Create(&in).Error
	return
}

func (impl *adminRoleService) Edit(in modeladmin.AdminRole) (err error) {
	err = storage.GDB1.Save(&in).Error
	return
}

func (impl *adminRoleService) DeleteByIdList(idList []int64) (err error) {
	err = storage.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&modeladmin.AdminRole{}, "id in ?", idList).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.AdminRoleMenu{}, "rid in ?", idList).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.AdminRolePolicy{}, "rid in ?", idList).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.CasbinRule{},
			"(ptype='g' AND v1 in ?) OR (ptype='p' AND v0 in ?)", idList, idList).Error; err != nil {
			return err
		}
		return nil
	})
	return
}

func (impl *adminRoleService) GetTable(in oin.VxeTableIn) (rows []*modeladmin.AdminRole, total int64, err error) {
	if err = storage.GDB1.Model(&modeladmin.AdminRole{}).Count(&total).Error; err != nil {
		return
	}
	if err = storage.GDB1.
		Offset(in.Offset()).Limit(in.PageSize).
		Find(&rows).Error; err != nil {
		return
	}
	return
}

func (impl *adminRoleService) GetList() (rows []*modeladmin.AdminRole, err error) {
	err = storage.GDB1.Find(&rows).Error
	return
}

func (impl *adminRoleService) Grant(in oinadmin.AdminRoleGrant) (err error) {
	var (
		policyList = make([]*modeladmin.AdminPolicy, 0)
		m1         = make([]*modeladmin.CasbinRule, 0)
		m2         = make([]*modeladmin.AdminRoleMenu, 0)
	)
	if err = storage.GDB1.Find(&policyList, "id in ?", in.PidList).Error; err != nil {
		return
	}
	if err = storage.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&modeladmin.CasbinRule{}, "ptype='p' AND v0 = ?", in.Rid).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.AdminRolePolicy{}, "rid = ?", in.Rid).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.AdminRoleMenu{}, "rid = ?", in.Rid).Error; err != nil {
			return err
		}
		//
		if in.Rid > 0 && len(policyList) > 0 {
			for _, v := range policyList {
				m1 = append(m1, &modeladmin.CasbinRule{
					Ptype: "p",
					V0:    strconv.FormatInt(in.Rid, 10),
					V1:    v.V1,
					V2:    v.V2,
					V3:    v.V3,
					V4:    v.V4,
					V5:    v.V5,
				})
			}
		}
		if err = tx.CreateInBatches(m1, 100).Error; err != nil {
			return err
		}
		for _, v := range in.PidList {
			if err = tx.Create(&modeladmin.AdminRolePolicy{
				Rid: uint(in.Rid),
				Pid: uint(v),
			}).Error; err != nil {
				return err
			}
		}

		if in.Rid > 0 && len(in.MidList) > 0 {
			for _, v := range in.MidList {
				if len(v.Bid) > 0 {
					for _, vv := range v.Bid {
						m2 = append(m2, &modeladmin.AdminRoleMenu{
							Rid: in.Rid,
							Mid: v.Id,
							Bid: vv,
						})
					}
				} else {
					m2 = append(m2, &modeladmin.AdminRoleMenu{
						Rid: in.Rid,
						Mid: v.Id,
					})
				}
			}
		}
		if err = tx.CreateInBatches(m2, 100).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		return
	}
	if err = icasbin.GCasbin.LoadPolicy(); err != nil {
		return
	}
	return
}

func (impl *adminRoleService) Owned(rid int64) (iris.Map, error) {
	var (
		err        error
		menuList   = make([]int64, 0)
		policyList = make([]int64, 0)
	)
	if err = storage.GDB1.Model(&modeladmin.AdminRoleMenu{}).Select("distinct mid").
		Where("rid=?", rid).
		Scan(&menuList).Error; err != nil {
		return nil, err
	}
	if err = storage.GDB1.Model(&modeladmin.AdminRolePolicy{}).Select("distinct pid").
		Where("rid=?", rid).
		Scan(&policyList).Error; err != nil {
		return nil, err
	}
	return iris.Map{
		"menuList":   menuList,
		"policyList": policyList,
	}, nil
}
